//
//  ReadDetailsTableViewController.m
//  Lesson_Read
//
//  Created by 李洪鹏 on 15-4-27.
//  Copyright (c) 2015年 ___蓝鸥科技公司___. All rights reserved.
//

#import "ReadDetailsTableViewController.h"
#import "ReadDetailsTableViewCell.h"
#import "ReadDetails.h"
#import "AFNetworking.h"
#import "ReadList.h"
#import "ReadDetails.h"
#import "UIImageView+WebCache.h"
#import "ReadWorksViewController.h"
#import "MJRefresh.h"



@interface ReadDetailsTableViewController ()

@property (nonatomic, retain)NSMutableArray *allDataArray;
@property (nonatomic, retain)NSMutableData *allData;

@property (nonatomic, assign)NSInteger number;

//声明私有方法
- (void)loadData;

@end

@implementation ReadDetailsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"阅读列表";
    
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:@"ReadDetailsTableViewCell" bundle:nil] forCellReuseIdentifier:@"ReadDetailsIdentifier"];
    
    //加载数据
    [self loadData];
   
    
    self.allDataArray = [NSMutableArray array];
    
    //MJ哥 刷新
    [self MJload];
    
    
}



- (void)MJload
{
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        [self.tableView.header beginRefreshing];
        
        [self loadNewData];
        [self.tableView.header endRefreshing];
    }];
    
    
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self.tableView.footer beginRefreshing];
        [self loadMoreData];
        
        [self.tableView.footer endRefreshing];
    }];
    
    
    
}

//上拉刷新
- (void)loadNewData
{
    [self.tableView.header endRefreshing];
}



- (void)loadData
{
    
    self.allDataArray = [NSMutableArray array];
    //__block typeof(self) weakself = self;
    
    
    // 获取网络数据
    NSString *str = [NSString stringWithFormat:@"http://api2.pianke.me/read/columns_detail"];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    
    NSString *paramDataString = [NSString stringWithFormat:@"typeid=%@&client=1&sort=hot&start=%ld",_readtypeId, (long)_number];
    
    NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"]; // 设置请求方式
    [request setHTTPBody:paramData]; // 设置参数
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    
    
}


//上拉加载
- (void)loadMoreData
{
    _number =  _number + 10;
    
    NSString *str = [NSString stringWithFormat:@"http://api2.pianke.me/read/columns_detail?"];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *paramDataString = [NSString stringWithFormat:@"typeid=%@&client=1&sort=hot&start=%ld",_readtypeId, (long)_number];
    
    NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"]; // 设置请求方式
    [request setHTTPBody:paramData]; // 设置参数
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.tableView.header endRefreshing];
    
    
    [self.tableView.footer endRefreshing];
 
    
    
}


#pragma mark -NSURLConnectionDataDelegate
#pragma mark 开始接受请求结果
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.allData = [NSMutableData data];
}

#pragma mark 接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [_allData appendData:data];
}

#pragma mark 数据接受完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    __block typeof(self) weakself = self;
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_allData options:NSJSONReadingAllowFragments error:nil];
    
    for (NSDictionary *item in dict[@"data"][@"list"]) {
        
        ReadDetails *read = [ReadDetails new];
        [read setValuesForKeysWithDictionary:item];
        [weakself.allDataArray addObject:read];
        
    }
    
    [weakself.tableView reloadData];
    
    
}

#pragma mark 发生错误,执行此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    return  _allDataArray.count;
   
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReadDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReadDetailsIdentifier" forIndexPath:indexPath];
    
    ReadDetails *read = _allDataArray[indexPath.row];
    
    
    cell.ReadDetailsTitle.text = read.title;
    cell.ReadDetailsIntroduce.text = read.content;
    
    [cell.ReadDetailsImage sd_setImageWithURL:[NSURL URLWithString:read.coverimg]];
    
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160;
    
    
}


//推出详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ReadDetails *read = _allDataArray[indexPath.row];
    
    ReadWorksViewController *readWorkVC = [[ReadWorksViewController new] autorelease];
    
    readWorkVC.contentId = read.id1;
    [self.navigationController pushViewController:readWorkVC animated:YES];
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



-(void)dealloc
{
    [_readtypeId release];
    [_allDataArray release];
    
    
    [super dealloc];
}


@end
